package com.cynteka.cyfoman.core.collection;

import com.cynteka.cyfoman.core.ComplexPropertyResolver;
import com.cynteka.cyfoman.core.IPropertyResolver;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Sergey
 * Date: 02.08.11
 * Time: 20:30
 */
public class RegexpPropertyResolver implements IPropertyResolver {
    private IPropertyResolver baseResolver = new ComplexPropertyResolver();
    private String baseProperty;
    private String regexp;
    private List<String> variables;
    private transient Pattern pattern;

    /**
     * Match(true) or find (false)
     */
    private boolean match = true;

    /**
     * Match(true) or find (false)
     */
    public boolean isMatch() {
        return match;
    }

    public void setMatch(boolean match) {
        this.match = match;
    }

    public List<String> getVariables() {
        return variables;
    }

    public void setVariables(List<String> variables) {
        this.variables = variables;
    }

    public String getRegexp() {
        return regexp;
    }

    public void setRegexp(String regexp) {
        this.regexp = regexp;
    }

    public String getBaseProperty() {
        return baseProperty;
    }

    public void setBaseProperty(String baseProperty) {
        this.baseProperty = baseProperty;
    }

    public IPropertyResolver getBaseResolver() {
        return baseResolver;
    }

    public void setBaseResolver(IPropertyResolver baseResolver) {
        this.baseResolver = baseResolver;
    }

    @Override
    public Object getProperty(Object object, String propertyName) {
        if (variables.contains(propertyName)) {
            // Regexp processing
            Object originalValue = baseResolver == null ? object : baseResolver.getProperty(object, baseProperty);
            String originalString = originalValue == null ? null : String.valueOf(originalValue);
            initPattern();
            Matcher m = pattern.matcher(originalString);
            boolean q = match ? m.matches() : m.find();
            if (q) {
                int idx = variables.indexOf(propertyName);
                String res = m.group(idx + 1);
                return res;
            }
            return null;
        } else {
            return baseResolver.getProperty(object, propertyName);
        }
    }

    private synchronized void initPattern() {
        if (pattern == null) {
            pattern = Pattern.compile(regexp);
        }
    }
}
